package com.info33.platform.business.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.info33.platform.business.app.dao.AppMenuDao;
import com.info33.platform.business.app.dao.AppTenantMenuDao;
import com.info33.platform.business.app.entity.AppMenu;
import com.info33.platform.business.app.entity.AppTenantMenu;
import com.info33.platform.business.app.service.AppMenuService;
import com.info33.platform.business.app.vo.AppMenuVO;
import com.info33.platform.common.exception.TransactionalException;
import com.info33.platform.common.mvc.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author admin
 */
@Service
public class AppMenuServiceImpl extends ServiceImpl<AppMenuDao, AppMenu> implements AppMenuService {

    @Autowired
    private AppMenuDao appMenuDao;
    @Autowired
    private AppTenantMenuDao appTenantMenuDao;

    @Override
    public Result<Object> pcAdd(AppMenu appMenu) {
        if (appMenuDao.insert(appMenu) != 1) {
            return Result.error(Result.RESULT_ERROR_PUBLIC_MSG);
        }
        AppTenantMenu atm = new AppTenantMenu();
        atm.setMenuId(appMenu.getId());
        atm.setRemarks(appMenu.getRemarks());
        if (appTenantMenuDao.insert(atm) != 1) {
            throw new TransactionalException();
        }
        return Result.ok();
    }

    @Override
    public Result<Object> pcDelete(Long mid) {
        Integer count = appTenantMenuDao.selectCount(new QueryWrapper<AppTenantMenu>().eq("menu_id", mid));
        if (count > 0) {
            return Result.error("已有 " + count + " 个租户，已分配此菜单，不可删除");
        }
        return this.removeById(mid) ? Result.ok() : Result.error();
    }

    @Override
    public List<AppMenuVO> pcTree() {
        List<AppMenuVO> appMenus = appMenuDao.getAll();
        List<AppMenuVO> collect = appMenus.stream().filter(l -> Math.abs(l.getPid()) == 1L).collect(Collectors.toList());
        collect.forEach(l -> l.setSons(appMenus.stream().filter(ll -> ll.getPid().equals(l.getId())).collect(Collectors.toList())));
        return collect;
    }
}